<template>
    <div>
        <div>
            <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules" v-if="+lubiaoDetail.status !== 3">
                <a-row>
                    <a-col :span="16">
                        <a-form-item label="审核意见" name="auditOpinion">
                            <div style="width: 100%">
                                <a-textarea
                                    v-model:value="form.auditOpinion"
                                    showCount
                                    :maxlength="500"
                                    auto-size
                                    v-if="isUserCanApprove || lubiaoDetail.status === '1'"
                                />
                                <span style="white-space: pre-wrap" v-html="form.auditOpinion" v-else />
                            </div>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            <flexbox justify="flex-end" style="padding-right: 12px" v-if="+lubiaoDetail.stage < 5 && +lubiaoDetail.status < +STATUS.COMPLETED">
                <a-button type="primary" :loading="saveLoading" @click="handleSave" v-if="+lubiaoDetail.stage <= +STAGE.PRODUCT_MANAGER && hasAuth"
                    >暂存</a-button
                >
                <a-button
                    type="primary"
                    :loading="startProcessLoading"
                    class="margin-l-8"
                    @click.stop="handleStartProcess"
                    v-if="lubiaoDetail.status === STATUS.DRAFT"
                >
                    发起
                </a-button>
                <!-- 团队长审核节点 -->
                <a-button
                    type="primary"
                    :loading="rejectToTeamLeaderLoading"
                    class="margin-l-8"
                    @click.stop="handleNextProcess('否')"
                    v-if="lubiaoDetail.stage === STAGE.TEAM_LEADER && isUserCanApprove"
                >
                    驳回
                </a-button>
                <!-- 产品管理团队 -->
                <a-button
                    type="primary"
                    :loading="rejectToTeamLeaderLoading"
                    class="margin-l-8"
                    @click.stop="handleNextProcess('否')"
                    v-if="lubiaoDetail.stage === STAGE.PRODUCT_MANAGEMENT && isUserCanApprove"
                >
                    驳回至团队长
                </a-button>
                <a-button
                    type="primary"
                    :loading="rejectToProductManagerLoading"
                    class="margin-l-8"
                    @click.stop="handleNextProcess('否至产品')"
                    v-if="lubiaoDetail.stage === STAGE.PRODUCT_MANAGEMENT && isUserCanApprove"
                >
                    驳回至产品经理
                </a-button>
                <a-button
                    type="primary"
                    :loading="approveLoading"
                    class="margin-l-8"
                    @click.stop="handleNextProcess('是')"
                    v-if="+lubiaoDetail.status > +STATUS.DRAFT && isUserCanApprove"
                >
                    通过
                </a-button>
            </flexbox>
        </div>
        <HistoryRecord :detail="lubiaoDetail" :historyList="historyList" v-if="historyList.length" />
    </div>
</template>

<script lang="ts">
import store from '@/store';
import api from '@/api';
import { message } from 'ant-design-vue';
import HistoryRecord from './HistoryRecord.vue';
import { defineComponent, ref, unref, reactive, toRefs, computed, watch, nextTick } from 'vue';

// stage阶段
const STAGE = {
    PRODUCT_MANAGER: '2', // 产品经理
    TEAM_LEADER: '3', // 团队长
    PRODUCT_MANAGEMENT: '4' // 产品管理团队
} as const;
// status状态
const STATUS = {
    DRAFT: '1', // 草稿
    IN_PROGRESS: '2', // 进行中
    COMPLETED: '3' // 完成
} as const;

interface ComponentState {
    form: {
        pass: string;
        auditOpinion: string;
    };
    historyList: any[];
    isUserCanApprove: boolean;
    saveLoading: boolean;
    startProcessLoading: boolean;
    rejectToTeamLeaderLoading: boolean;
    rejectToProductManagerLoading: boolean;
    approveLoading: boolean;
}
export default defineComponent({
    name: 'ApprovalProcess',
    components: {
        HistoryRecord
    },
    props: {
        lubiaoDetail: {
            type: Object,
            default: () => ({})
        },
        // 是否是产品负责人
        hasAuth: {
            type: Boolean,
            default: false
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const ruleFormRef = ref<any>({});
        const state = reactive<ComponentState>({
            form: {
                pass: '',
                auditOpinion: ''
            },
            historyList: [],
            isUserCanApprove: false,
            saveLoading: false,
            startProcessLoading: false,
            rejectToTeamLeaderLoading: false, // 更改为更语义化的名称
            rejectToProductManagerLoading: false,
            approveLoading: false
        });
        const rules = computed(() => {
            const rules = {
                auditOpinion: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }]
            };
            return +props.lubiaoDetail.stage > +STAGE.PRODUCT_MANAGER && ['否', '否至产品'].includes(state.form.pass) ? rules : {};
        });
        // 获取审批信息
        const getHistoryList = async () => {
            const query = {
                instanceId: props.lubiaoDetail.instanceId,
                type: 'signpost'
            };
            const { success, moule, errorMsg } = await api.historyModel.historyOperationByInstanceId(query);
            if (success) {
                if (moule && moule.length) {
                    state.historyList = [...moule];
                    checkIsUserCanApprove();
                }
            } else {
                message.error(errorMsg);
            }
        };
        const checkIsUserCanApprove = () => {
            let assigneeName = '';
            const userName = store.getters.userInfo.employeeDTO.name;
            if (state.historyList.length) {
                assigneeName = state.historyList[state.historyList.length - 1].assigneeName;
            }
            state.isUserCanApprove = assigneeName ? assigneeName.indexOf(userName) >= 0 : true;
        };
        //暂存
        const handleSave = async () => {
            state.saveLoading = true;
            store.commit('app/SET_GLOBALLOADING', true);
            try {
                const query = { ...props.lubiaoDetail };
                const { success } = await api.signpostModel.save(query);
                if (success) {
                    message.success('保存成功');
                }
            } finally {
                state.saveLoading = false;
                store.commit('app/SET_GLOBALLOADING', false);
            }
        };

        const handleValidate = () => {
            return new Promise((res) => {
                unref(ruleFormRef)
                    .validate()
                    .then(
                        () => {
                            res(true);
                        },
                        () => {
                            res(false);
                        }
                    );
            });
        };
        // 审批
        const handleNextProcess = async (pass: string) => {
            let loadingKey: keyof ComponentState;
            if (pass === '是') {
                loadingKey = 'approveLoading';
            } else if (pass === '否至产品') {
                loadingKey = 'rejectToProductManagerLoading';
            } else {
                loadingKey = 'rejectToTeamLeaderLoading';
            }
            state[loadingKey] = true;
            store.commit('app/SET_GLOBALLOADING', true);
            state.form.pass = pass;

            try {
                await nextTick();
                const isValid = await handleValidate();
                if (isValid) {
                    const query = { ...props.lubiaoDetail, ...state.form };
                    const { success, errorMsg } = await api.signpostModel.auditProcess(query);
                    if (success) {
                        message.success('操作成功');
                        emit('success');
                    } else {
                        message.error(errorMsg);
                    }
                }
            } finally {
                state[loadingKey] = false;
                store.commit('app/SET_GLOBALLOADING', false);
            }
        };
        //发起
        const handleStartProcess = async () => {
            if (!props.lubiaoDetail.verMgtId) {
                message.error('支线版本不能为空');
                return;
            }
            state.startProcessLoading = true;
            store.commit('app/SET_GLOBALLOADING', true);
            try {
                const query = { ...props.lubiaoDetail, ...state.form };
                const { success, errorMsg } = await api.signpostModel.startProcess(query);
                if (success) {
                    emit('success');
                } else {
                    message.error(errorMsg);
                }
            } finally {
                state.startProcessLoading = false;
                store.commit('app/SET_GLOBALLOADING', false);
            }
        };
        watch(
            () => props.lubiaoDetail,
            (n) => {
                if (n.instanceId) {
                    getHistoryList();
                }
            },
            { immediate: true }
        );
        return {
            ruleFormRef,
            rules,
            ...toRefs(state),
            handleSave,
            handleNextProcess,
            handleStartProcess,
            STAGE,
            STATUS
        };
    }
});
</script>

<style scoped></style>
